import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

var options = BaseOptions(connectTimeout: 5000, receiveTimeout: 5000);
var dio = Dio(options);

const String method_get = "get";
const String method_post = "post";

typedef void VoidRequestCallBack(String statusCode, dynamic data, Error error);

Future http(
    {@required String url,
    String method = method_get,
    Map<String, dynamic> params,
    int timeout = 5000,
    String contentType = Headers.jsonContentType,
    VoidRequestCallBack requestCallBack}) async {
  try {
    // 参数设置
    Options options = Options(
      responseType: ResponseType.json,
      sendTimeout: timeout,
      receiveTimeout: timeout,
      method: method,
      contentType: contentType,
    );

    Response response = await dio.request(
      url,
      queryParameters: params,
      options: options,
    );

    if (response != null) {
      requestCallBack("0", response.data, null);
    } else {
      // 未知错误！
      requestCallBack("-1", null, Error());
    }
  } catch (e) {
    requestCallBack("-1", null, Error());
  }
}

String errorMessage(DioErrorType statusCode) {
  switch (statusCode) {
    case DioErrorType.CONNECT_TIMEOUT:
      return "网络连接超时，请检查网络设置";
      break;
    case DioErrorType.RECEIVE_TIMEOUT:
      return "服务器异常，请稍后重试！";
      break;
    case DioErrorType.SEND_TIMEOUT:
      return "网络连接超时，请检查网络设置";
      break;
    case DioErrorType.RESPONSE:
      return "服务器异常，请稍后重试！";
      break;
    case DioErrorType.CANCEL:
      return "请求已被取消，请重新请求";
      break;
    case DioErrorType.DEFAULT:
      return "网络异常，请稍后重试！";
      break;
    default:
  }
  return "网络异常，请稍后重试！";
}
